package com.ruoyi.project.wechatprogram.wxcategory.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.wechatprogram.categorymenu.domain.WxCategoryMenu;
import com.ruoyi.project.wechatprogram.categorymenu.service.IWxCategoryMenuService;
import com.ruoyi.project.wechatprogram.wxcategory.mapper.WxCategoryMapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.wechatprogram.wxcategory.domain.WxCategory;
import com.ruoyi.project.wechatprogram.wxcategory.service.IWxCategoryService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 类目Controller
 * 
 * @author csx
 * @date 2020-03-27
 */
@Controller
@RequestMapping("/wechatprogram/wxCategory")
public class WxCategoryController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(WxCategoryController.class);

    private String prefix = "wechatprogram/wxCategory";

    @Autowired
    private IWxCategoryService wxCategoryService;

    @Autowired
    private IWxCategoryMenuService wxCategoryMenuService;

    @Autowired
    private WxCategoryMapper wxCategoryMapper;

    @RequiresPermissions("wechatprogram:wxCategory:view")
    @GetMapping()
    public String wxCategory()
    {
        return prefix + "/wxCategory";
    }

    /**
     * 查询类目列表
     */
    @RequiresPermissions("wechatprogram:wxCategory:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxCategory wxCategory)
    {
        startPage();
        List<WxCategory> list = wxCategoryService.selectWxCategoryList(wxCategory);
        return getDataTable(list);
    }

    /**
     * 导出类目列表
     */
    @RequiresPermissions("wechatprogram:wxCategory:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WxCategory wxCategory)
    {
        List<WxCategory> list = wxCategoryService.selectWxCategoryList(wxCategory);
        ExcelUtil<WxCategory> util = new ExcelUtil<WxCategory>(WxCategory.class);
        return util.exportExcel(list, "wxCategory");
    }

    /**
     * 新增类目
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存类目
     */
    @RequiresPermissions("wechatprogram:wxCategory:add")
    @Log(title = "类目", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WxCategory wxCategory)
    {
        try{
            if(StrUtil.isEmpty(wxCategory.getCategoryName())){
                return error("类目名称不能为空！");
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            String start=wxCategory.getStarttime();
            String end=wxCategory.getEndtime();
            Date startTime=dateFormat.parse(start);
            Date endTime=dateFormat.parse(end);
            if(startTime.after(endTime)){
                return error("就餐开始时间不能小于结束时间");
            }
            wxCategory.setRepastStarttime(startTime);
            wxCategory.setRepastEndtime(endTime);
            //如果类目type为null则设置为1，如果不为1，查询最大的+1为type
            Integer maxCategoryType = wxCategoryMapper.selectWxCategoryMaxCategoryType(null);
            wxCategory.setCategoryType(maxCategoryType);
        }catch (Exception e) {
            log.error("类目表添加异常", e);
        }
        return toAjax(wxCategoryService.insertWxCategory(wxCategory));
    }

    /**
     * 修改类目
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        WxCategory wxCategory = wxCategoryService.selectWxCategoryById(id);
        mmap.put("wxCategory", wxCategory);
        return prefix + "/edit";
    }

    /**
     * 修改类目
     */
    @GetMapping("/editmenu/{id}")
    public String editmenu(@PathVariable("id") Integer id, ModelMap mmap)
    {
        WxCategory wxCategory = wxCategoryService.selectWxCategoryById(id);
        mmap.put("menus", wxCategoryMenuService.selectWxCategoryMenuById(id));
        mmap.put("wxCategory", wxCategory);
        return prefix + "/editmenu";
    }

    /**
     * 修改保存类目
     */
    @RequiresPermissions("wechatprogram:wxCategory:edit")
    @Log(title = "类目", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WxCategory wxCategory)
    {
        try{
            if(StrUtil.isEmptyIfStr(wxCategory.getCategoryName())){
                return error("类目名称不能为空！");
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            String start=wxCategory.getStarttime();
            String end=wxCategory.getEndtime();
            Date startTime=dateFormat.parse(start);
            Date endTime=dateFormat.parse(end);
            if(startTime.after(endTime)){
                return error("就餐开始时间不能小于结束时间");
            }
            wxCategory.setRepastStarttime(startTime);
            wxCategory.setRepastEndtime(endTime);
        }catch (Exception e) {
            log.error("类目表修改异常", e);
        }
        return toAjax(wxCategoryService.updateWxCategory(wxCategory));
    }

    /**
     * 修改保存类目
     */
    @RequiresPermissions("wechatprogram:wxCategory:editmenu")
    @Log(title = "类目", businessType = BusinessType.UPDATE)
    @PostMapping("/editmenu")
    @ResponseBody
    public AjaxResult editmenuSave(Integer categoryId, String menuIds) {
        try{
            // 判空
            if (categoryId == null) {
                log.debug("餐品类型绑定菜品失败！");
                return AjaxResult.error("绑定菜品失败！");
            }
            if (StrUtil.isEmpty(menuIds)) {
                log.debug("每日菜单添加菜品为空！");
                return AjaxResult.error("绑定菜品失败！");
            }
            WxCategoryMenu wxCategoryMenu = null;
            String[] menuIdStr = menuIds.replace("，", ",").split(",");
            for (String str : menuIdStr) {
                // 保存餐品周期菜单
                wxCategoryMenu = new WxCategoryMenu();
                wxCategoryMenu.setCategoryId(categoryId);
                wxCategoryMenu.setMenuId(Integer.parseInt(str));
                wxCategoryMenu.setCreateBy(ShiroUtils.getLoginName());
                wxCategoryMenu.setCreateTime(new Date());
                Integer successStatus = wxCategoryMenuService.insertWxCategoryMenu(wxCategoryMenu);
                if (successStatus <= 0) {
                    log.error("插入失败，数据为：" + wxCategoryMenu.toString());
                    return AjaxResult.error("插入失败!");
                }
            }
        }catch (Exception e) {
            log.error("类目表修改异常", e);
        }
        return AjaxResult.success("绑定菜品成功！");
    }

    /**
     * 删除类目
     */
    @RequiresPermissions("wechatprogram:wxCategory:remove")
    @Log(title = "类目", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(wxCategoryService.deleteWxCategoryByIds(ids));
    }


    /**
     * 餐品类型显示
     */
    @RequiresPermissions("wechatprogram:menu:publish")
    @Log(title = "餐品类型列表", businessType = BusinessType.UPDATE)
    @PostMapping("/publishCategory/{id}")
    @ResponseBody
    public AjaxResult publishCategory(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        WxCategory wxCategory = new WxCategory();
        wxCategory.setId(id);
        wxCategory.setCategoryStatus(WxCategory.CATEGORY_STATUS_SHOW);
        if (wxCategoryService.updateWxCategory(wxCategory) <= 0) {
            return AjaxResult.error("操作异常！");
        }
        return AjaxResult.success("餐品类型显示成功！");
    }

    /**
     * 餐品类型隐藏
     */
    @RequiresPermissions("wechatprogram:menu:uppublish")
    @Log(title = "餐品类型列表", businessType = BusinessType.UPDATE)
    @PostMapping("/unPublishCategory/{id}")
    @ResponseBody
    public AjaxResult unPublishCategory(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        WxCategory wxCategory = new WxCategory();
        wxCategory.setId(id);
        wxCategory.setCategoryStatus(WxCategory.CATEGORY_STATUS_HIDE);
        if (wxCategoryService.updateWxCategory(wxCategory) <= 0) {
            return AjaxResult.error("操作异常！");
        }
        return AjaxResult.success("餐品类型隐藏成功！");
    }
}
